﻿using System;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Framework.Model;
using MvcApplication1.Framework;
using MvcApplication1.Models;
using MvcApplication1.Services;
using System.Linq;

namespace MvcApplication1.Controllers
{
    public class CharacterController : Controller
    {
        public ActionResult Create()
        {
            var character = new Character();
            return View("Edit", character);
        }

        public ActionResult Edit(int characterId)
        {
            var repository = new Repository(new ConnectionStringLoader(), new CacheWrapper());
            var character = repository.Get<Character>(characterId);
            return View(character);
        }

        public ActionResult Save(Character character)
        {
            try
            {
                var repository = new Repository(new ConnectionStringLoader(), new CacheWrapper());

                foreach (var tag in character.Tags.Where(c => c.Tag.Id == 0))
                    repository.Save(tag.Tag);

                repository.Save(character);

                foreach (var relationship in character.Relationships)
                {
                    var relatedCharacter = repository.Get<Character>(relationship.RelatedCharacterId.Value);
                    var reverseRelationship = relatedCharacter.Relationships.FirstOrDefault(r => r.RelatedCharacterId == character.Id);
                    if (reverseRelationship == null)
                    {
                        relatedCharacter
                            .Relationships
                            .Add(new Relationship
                                     {
                                         RelatedCharacterId = character.Id,
                                         RelationshipType = repository.Get<RelationshipType>(relationship.RelationshipType.ReverseRelationshipTypeId)
                                     });
                        repository.Save(relatedCharacter);
                    }
                }
            }
            catch (Exception e)
            {
                return Json(new {Success = false, Error = e.Message});
            }
            return Json(new {Success = true, Model = new JavaScriptSerializer().Serialize(character)});
        }

        public ActionResult Delete(int characterId)
        {
            try
            {
                var repository = new Repository(new ConnectionStringLoader(), new CacheWrapper());
                repository.Delete<Character>(s => s.Id == characterId);
                return Json(new {Success = true}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return Json(new {Success = false, Error = e.Message}, JsonRequestBehavior.AllowGet);
            }
        }
    }
}